// pages/pointsShopCar/pointsShopCar.js
const { getShoppingCarts, payShoppingPoints, changeShoppingCarts, getUserAllAddress } = require("../../utils/api");
const app = getApp()
import Dialog from '@vant/weapp/dialog/dialog';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    header: {
      title: '购物车',
      whiteBg: false,
      mode: 'back',
      navBarHeight: app.globalData.navBarHeight
    },
    active:1,
    isPoup:false,
    isBg: false,
    userInfo: null,
    list:['新品','周转','维护'],
    shopCart: null,
    sumPoints: 0,
    addressPopup: false, 
    address: [],
    activeAddressIndex: 0,
    submitBarTopHeight: null
  },

  // 页面初始化购物车数据
  getShoppingCarts() {
    const data = { PhoneNumber: this.data.userInfo.phoneNumber };
  
    getShoppingCarts(data).then(res => {
      if (res.code == 4005010) {
        // 对 res.data 中的每个对象添加 checked 属性
        const updatedData = res.data.map(item => ({
          ...item, // 复制当前对象的所有属性
          checkStatus: false // 添加 checked 属性，默认值为 false
        }));
  
        // 更新页面数据
        this.setData({
          shopCart: updatedData,
        });
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
        });
      }
    });
  },
  //购物车结算
  payShoppingPoints() {
    const shoppingNumberList = []
    this.data.shopCart.forEach(function(item) {
      if (item.checkStatus || item.checkStatus === 'allTrue') {
        shoppingNumberList.push(item.shoppingNumber)
      }
    });
    if (shoppingNumberList.length === 0 ) {
      wx.showToast({
        title: '请选择结算商品！',
        icon: 'none'
      })
      return
    }
    const data = { PhoneNumber: this.data.userInfo.phoneNumber,
      ShoppingNumberList: JSON.stringify(shoppingNumberList),
      Address: this.data.address[this.data.activeAddressIndex].address,
      UserName: this.data.address[this.data.activeAddressIndex].userName,
      UserPhoneNumber: this.data.address[this.data.activeAddressIndex].userPhoneNumber,
    };
    payShoppingPoints(data).then(res =>{
      if (res.code == 4006000) {
        this.getShoppingCarts()
        Dialog.alert({
          message: '结算成功',
          theme: 'round-button',
        }).then(() => {
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
        });
      }
    })
  },
  
  //商品选中状态更新
  checkStatusChange(e) {
    const index = e.currentTarget.dataset.value;
    let shopCart = this.data.shopCart;
    if (shopCart[index].checkStatus === 'allTrue') {
      shopCart = shopCart.map(item => {
        return {
          ...item,
          checkStatus: true
        }
      });
    }
    shopCart[index].checkStatus = !shopCart[index].checkStatus;
    if (shopCart.every(item => item.CheckStatus === true)) {
      shopCart = shopCart.map(item => {
        return {
          ...item,
          checkStatus: 'allTrue'
        }
      });
    };
    const filteredItems = shopCart.filter(item => item.checkStatus === true || item.checkStatus === 'allTrue');
    const totalPoints = filteredItems.reduce((sum, item) => sum + Number(item.needUsePoints), 0);
    this.setData({
      shopCart: shopCart,
      sumPoints: totalPoints
    });
  },
  //商品数量增加
  goodsNumberAdd(e) {
    const index = e.currentTarget.dataset.value;
    const data = { PhoneNumber: this.data.userInfo.phoneNumber, 
      BuyWay: this.data.shopCart[index].buyWay,
      Size: this.data.shopCart[index].size + 1,
      ShoppingNumber: this.data.shopCart[index].shoppingNumber,
    };
    changeShoppingCarts(data).then(res =>{
      if (res.code == 4005030) {
        this.setData({
          [`shopCart[${index}].Size`]: this.data.shopCart[index].size + 1,
        });
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
        });
      }
    });
  },
  //商品数量减少
  goodsNumberSubtract(e) {
    const index = e.currentTarget.dataset.value;
    const data = { PhoneNumber: this.data.userInfo.phoneNumber, 
      BuyWay: this.data.shopCart[index].buyWay,
      Size: this.data.shopCart[index].Size - 1,
      ShoppingNumber: this.data.shopCart[index].shoppingNumber,
    };
    changeShoppingCarts(data).then(res =>{
      if (res.code == 4005030) {
        this.setData({
          [`shopCart[${index}].Size`]: this.data.shopCart[index].size - 1,
        });
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
        });
      }
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      userInfo: wx.getStorageSync('userInfo')
    })
    this.getShoppingCarts()
    this.getUserAllAddress()
  },

  onReady() {

  },

  onPageScroll(e) {
    this.setData({
      'header.whiteBg': e.scrollTop < 40 ? false : true
    })
  },

  changeAllGoodsChecked(e) {
    console.log(e)
    const status = e.currentTarget.dataset.value;
    let shopCart = this.data.shopCart;
    if (status === 'allTrue') {
      shopCart = shopCart.map(item => {
        return {
          ...item,
          checkStatus: false
        }
      });
    } else {
      shopCart = shopCart.map(item => {
        return {
          ...item,
          checkStatus: 'allTrue'
        }
      });
    }
    const filteredItems = shopCart.filter(item => item.checkStatus === true || item.checkStatus === 'allTrue');
    const totalPoints = filteredItems.reduce((sum, item) => sum + Number(item.needUsePoints), 0);
    this.setData({
      shopCart: shopCart,
      sumPoints: totalPoints
    });
  },

  getUserAllAddress() {
    getUserAllAddress({PhoneNumber: this.data.userInfo.phoneNumber}).then(res => {
      if (res.code === 4007010) {
        let activeAddressIndex = 0;
        const address = res.data.map((item,index) =>{
          if (item.default === 1) { activeAddressIndex = index }
          return{
            ...item,
            checked: false
          }
        })
        this.setData({
          address: address,
          activeAddressIndex: activeAddressIndex
        })
        if (address.length === 0) {
          this.setData({
            'address[0].Address': "暂无地址，请点此跳转至新增页面。"
          })
        }
      } else {
        wx.showToast({
          title: '地址获取失败' + res.msg,
        })
      }
    });
  },

  addressOpen() {
    if (this.data.address[0].Address === "暂无地址，请点此跳转至新增页面。") {
      wx.redirectTo({
        url: '/pages/address/address?addNewAddressPopup=true',
      })
      return
    }
    this.setData({
      addressPopup: true
    })
  },

  addressClose() {
    this.setData({
      addressPopup: false
    })
  },

  activeAddress(e) {
    this.setData({
      activeAddressIndex: e.currentTarget.dataset.index
    })
  }
})